package com.xge.business.utils

import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs

object DateDiffUtils {

    data class DayResult(val days: Int, val type: String) // type: "past" 或 "future"

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).apply {
        isLenient = false
    }

    /**
     * 传入格式为 yyyy-MM-dd 的日期，返回与今天相差的天数以及类型
     */
    fun getDaysFromToday(dateStr: String): DayResult? {
        return try {
            val inputDate = dateFormat.parse(dateStr) ?: return null
            val today = getZeroTime(Date())
            val target = getZeroTime(inputDate)

            val diffMillis = target.time - today.time
            val diffDays = (diffMillis / (1000 * 60 * 60 * 24)).toInt()

            when {
                diffDays > 0 -> DayResult(diffDays, "future") // 还剩多少天
                diffDays < 0 -> DayResult(abs(diffDays), "past")   // 已经过去多少天
                else -> DayResult(0, "today")
            }
        } catch (e: Exception) {
            null
        }
    }

    // 获取去除时分秒的日期
    private fun getZeroTime(date: Date): Date {
        val cal = Calendar.getInstance().apply {
            time = date
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        return cal.time
    }
}
